/* banners的数据结构(PostgreSQL)
CREATE TABLE "public"."banners" (
  "id" int4 NOT NULL DEFAULT nextval('banners_id_seq'::regclass),
  "image_url" varchar(255) COLLATE "pg_catalog"."default",
  "title_zh" varchar(255) COLLATE "pg_catalog"."default",
  "title_en" varchar(255) COLLATE "pg_catalog"."default",
  "content_zh" varchar(255) COLLATE "pg_catalog"."default",
  "content_en" varchar(255) COLLATE "pg_catalog"."default",
  "model" varchar(255) COLLATE "pg_catalog"."default",
  "doc_id" int4,
  CONSTRAINT "banners_pkey" PRIMARY KEY ("id")
);
*/

const Router = require("@koa/router");
const { Pool } = require("pg");
const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../.env') });
const router = new Router({ prefix: "/banners" });

// 配置数据库连接池
const pool = new Pool({
  user: process.env.DB_USER,
  host: process.env.DB_HOST,
  database: process.env.DB_DATABASE,
  password: process.env.DB_PASSWORD,
  port: process.env.DB_PORT,
});

// 获取banners列表（支持分页）
router.get('/', async (ctx) => {
  try {
    // 从查询参数获取分页信息，默认第1页，每页10条
    const page = parseInt(ctx.query.page) || 1;
    const limit = parseInt(ctx.query.limit) || 10;
    const offset = (page - 1) * limit;

    // 查询总记录数
    const countResult = await pool.query('SELECT COUNT(*) FROM banners');
    const total = parseInt(countResult.rows[0].count);

    // 查询当前页数据
    const result = await pool.query(
      'SELECT * FROM banners ORDER BY id ASC LIMIT $1 OFFSET $2',
      [limit, offset]
    );

    ctx.body = {
      success: true,
      data: result.rows,
      pagination: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit)
      }
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取banners列表失败: ' + error.message
    };
  }
});

module.exports = router;